package com.lagou.edu.wwyan.web1.minicat;

import java.io.File;
import java.io.IOException;
import java.net.Socket;
import java.util.Map;

public class RequestProcessor extends Thread{
    private Socket socket;
    private Mapper mapper;
//    private Map<String,Servlet> servletMap;
//
//    public RequestProcessor(Socket socket, Map<String, Servlet> servletMap) {
//        this.socket = socket;
//        this.servletMap = servletMap;
//    }

    public RequestProcessor(Socket socket, Mapper mapper) {
        this.socket = socket;
        this.mapper = mapper;
    }

    @Override
    public void run() {
        try {
            Request request = new Request(socket.getInputStream());
            Response response = new Response(socket.getOutputStream());
//            Servlet servlet = servletMap.get(request.getUrl());
//            Servlet servlet = servletMap.get(request.getUrl());
            MappingData mappingData = new MappingData();
            mapper.map(request.getHost(),request.getUrl(),mappingData);
            Wrapper wrapper = mappingData.getWrapper();
            Servlet servlet = wrapper == null ? null : wrapper.getServlet();
            if (servlet == null){
                //如果找不到servlet，尝试返回静态页面
                if (mappingData.getHost() == null ) {
                    response.outputStatic(request.getUrl());
                }else {
                    String appBase = mappingData.getHost().getAppBase();
                    String path = appBase + request.getUrl();

                    response.outputAbsolutePath(path);
                }
            }else {
                servlet.service(request,response);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
